<template>
    <div class="container" >
        <!-- 导航 -->
        <div class="nav">
            新建问卷调查
            <div class="nav-btn fr">
                <a @click="detail">预览</a>
                <a @click="savePaper">保存</a>
                <a class="completeBtn" @click="saveAndrelease">保存并发布</a>
            </div>
        </div>
        <div class="placeholder">
        </div>
        <div class="body mar-top"  v-loading="loading"  element-loading-text="拼命加载中">
            <div class="main box paper_title">
                <div class="label">
                    问卷标题：
                </div>
                <div class="input">
                    <el-input v-model="questionPaper.title">

                    </el-input>
                </div>
            </div>
            <div class="main  editArea">
                
                <div class="left box">
                    <div class="question" @click="editQuestion(index)" v-for="(question,index) in questionPaper.questions" :key="index">
                        
                        <div class="number">
                            {{question.index  + 1}}
                        </div>
                        <div class="title">{{question.name}}</div>
                        <div class="control">
                            <i class="el-icon-delete" @click.stop="deleteQuestion(index)"></i>
                        </div>
                    </div>
                </div>  
                <div class="right">

                    <div class="box new-title">
                        <div class="label">选择题型：</div>
                        <div>
                            <el-button size="medium" round @click="switchType(1)">单选题</el-button>
                        </div>
                        <div>
                            <el-button size="medium" round @click="switchType(2)">多选题</el-button>
                        </div>
                        <div>
                            <el-button size="medium" round @click="switchType(0)">文本题</el-button>
                        </div>

                    </div>
                  
                    <div class="box new-content">
                        <el-form v-if="formData.type==1 || formData.type==2 " :model="formData" size="small"  ref="dataForm" >
                             <!-- 题目序号 -->
                            <el-row class="title_row">
                                <span class="q_number">{{formData.index  + 1}}</span>
                                <span class="q_name" >{{formData.type==1?'(单选)':'(多选)'}}</span>
                            
                            </el-row>
                            <!-- 题干 -->
                            <el-row>
                           
                                    <el-form-item :rules="rules" label="题干" prop="name" >
                                        <el-input 
                                            type="textarea"
                                            :rows="2"
                                            placeholder="输入问卷题干"
                                            v-model="formData.name">
                                        </el-input>
                                    </el-form-item>
                            </el-row>
                            <!-- 选项列表-->
                            <el-row>
                                <div class="options">
                                    <div class="option" v-for="(option,index) in formData.options" :key="index">
                                        <!-- 选项序号 -->
                                       <div class="option_number">
                                            {{getLetter(index)}}
                                       </div>
                                       <!-- 选项内容 -->
                                       <div class="option_text">
                                             <el-form-item
                                                :rules="rules"  
                                                :prop="'content_'+index">
                                                <el-input
                                                    v-model="formData['content_' + index]"
                                                    placeholder="选项内容"
                                                 >
                                                </el-input>
                                            </el-form-item>
                                       </div>
                                       <!-- 选项分值-->
                                       <div class="option_score">
                                            <el-form-item  
                                                :rules="rules"  
                                                :prop="'score_'+index">
                                                <el-input
                                                    type="text"
                                                    v-model="formData['score_' + index]"
                                                 >
                                                 <template slot="suffix">分</template>
                                                </el-input>
                                                
                                            </el-form-item>
                                       </div>
                                       <!-- 删除选项 -->
                                        <div class="deleteOption">
                                            <el-button  type="text" @click="deleteOption(index)"><i class="el-icon-close"></i></el-button>
                                        </div>
                                    </div>
                                </div>
                                <div class="addOption">
                                    <el-button icon="el-icon-plus" type="text" @click="addNewOption">添加选项</el-button>
                                </div>
                            </el-row>
                        </el-form>
                        <el-form v-if="formData.type==0  " :model="formData" size="small"  ref="dataForm">
                                 <!-- 题目序号 -->
                            <el-row class="title_row">
                                <span class="q_number">{{formData.index + 1}}</span>
                                <span class="q_name" >(文本)</span>
                            
                            </el-row>

                            <!-- 题干 -->
                            <el-row>
                           
                                    <el-form-item :rules="rules" label="题干" prop="name" >
                                        <el-input 

                                            type="textarea"
                                            :rows="2"
                                            placeholder="输入问卷题干"
                                            v-model="formData.name">
                                        </el-input>
                                    </el-form-item>
                            </el-row>
                        </el-form>
                        <div class="btns">
                            <el-button round >重置</el-button>
                            <el-button type="primary" round @click="submitForm('dataForm')">完成</el-button>
                        </div>
                    </div>
                </div>
            </div>
            
        </div>
    </div>
</template>

<script>
// import { save,get} from "@/api/questionnaire/questionnaire";
import { add,update,get} from "@/api/questionnaire/question";

export default {
    data() {
        return {
            rules:[{ required: true, message: '此项必填', trigger: 'blur' }],
            formData:{
                index:0,
                type:1,
                name:"",
                options:[{},{},{},{}]

            },

            questionPaper:{
                title:"辅导员满意度问卷调查",
                questions:[]
            },
            loading:false,

            
        };
    },
    created(){
        var date = new Date();
        var year = date.getFullYear();
        this.questionPaper.title =year +"年度辅导员满意度问卷调查" 
      
        if(this.$route.query.id){
            this.loading = true;
            get(this.$route.query.id).then(res=>{
            if(res.code == 200 && res.data){
                let data = {};
                Object.assign(data,{
                            questions:JSON.parse(res.data.questions),
                            title:res.data.title,
                id:res.data.id});
                console.log(data);
                this.questionPaper = data;
        
                for(let i = 0; i < this.questionPaper.questions.length;i++){
                    let type = this.questionPaper.questions[i].type;
                    let options = this.questionPaper.questions[i].options;
            
                    //单选或多选的话构建选项数组
                    if( type == 1 ||  type == 2 ){
                        for(let j = 0;j < options.length ;j ++ ){
                            this.questionPaper.questions[i]['content_'+ j] =this.questionPaper.questions[i].options[j].content;
                            this.questionPaper.questions[i]['score_'+ j] = this.questionPaper.questions[i].options[j].score ;

                        
                        }
                    }
                }
            }
            this.loading = false;
        })
        }
        
    },
    methods:{
        //保存并且发布
        saveAndrelease(){
            this.tansPaper();

              let data = {};
                Object.assign(data,{
                    questions:JSON.stringify(this.questionPaper.questions),
                    title:this.questionPaper.title,
                    id:this.questionPaper.id});
            this.loading = true;
            if(this.questionPaper.id !=null && this.questionPaper.id != ""){
                data.status ='1';
                update(data).then(res=>{
                    this.loading = false;
                    if(res.code == 200){
                        //先保存
                        this.$modal.msgSuccess(res.msg);
                    }else{
                          this.$modal.msgError("操作失败");
                    }

                });
            }else{
                add(data).then(res=>{
                    this.loading = false;
                    if(res.code == 200){
                       this.questionPaper.id = res.data.id;
                        //先保存
                        this.$router.push({
                            path: 'release', 
                            params:  { id: this.questionPaper.id} 
                        });
                    }else{
                        this.$modal.msgSuccess(res.msg);
                    }

                });
            }
        
        },
        //预览问卷
        detail(){
            this.tansPaper();
            sessionStorage.setItem("paper",JSON.stringify(this.questionPaper));
            this.$router.push({
                    path: 'detail',
            });
              
        },
        // 保存问卷
        savePaper(){
            if(!this.questionPaper.title){
                this.$alert(
                    '问卷标题未填写', '消息提示', {
                    confirmButtonText: '确定',
                    type: 'error'
                });
                return;
            }

            if(this.questionPaper.questions.length < 1){
                this.$alert(
                    '问卷无题目', '消息提示', {
                    confirmButtonText: '确定',
                    type: 'error'
                });
                return;
            }
            this.tansPaper();
            this.loading = true;
            let data = {};
            Object.assign(data,{
                questions:JSON.stringify(this.questionPaper.questions),
                title:this.questionPaper.title,
                id:this.questionPaper.id})
            
            if(this.questionPaper.id !=null && this.questionPaper.id != ""){
                update(data).then(res=>{
                    if(res.code == 200){
                        this.$modal.msgSuccess("保存成功");
                        this.$refs.dataForm.resetFields();
                           this.questionPaper.id = res.data.id;
                        this.switchType(this.formData.type);
                    }else{
                        this.$modal.msgSuccess(res.msg);
                    }
                 this.loading = false;
                });
            }else{
                add(data).then(res=>{
                    if(res.code == 200){
                          this.questionPaper.id = res.data.id;
                        this.$modal.msgSuccess("保存成功");
                        this.$refs.dataForm.resetFields();
                        this.switchType(this.formData.type);
                    }else{
                        this.$modal.msgSuccess(res.msg);
                    }
                    this.loading = false;
                });
            }
            // save(this.questionPaper).then(res=>{
            //    if(res.code == 200){
            //         this.$modal.msgSuccess("保存成功");
            //         this.$refs.dataForm.resetFields();
            //         this.switchType(this.formData.type);
            //    }else{
            //         this.$modal.msgSuccess(res.msg);
            //    }
            //      this.loading = false;
      
            // });

        },
        tansPaper(){
             for(let i = 0; i < this.questionPaper.questions.length;i++){
                let type = this.questionPaper.questions[i].type;
                let options = this.questionPaper.questions[i].options;
         
                //单选或多选的话构建选项数组
                if( type == 1 ||  type == 2 ){
                    for(let j = 0;j < options.length ;j ++ ){
                        //选项内容
                        let content = this.questionPaper.questions[i]['content_'+ j];
                        //选项分数
                        let score = this.questionPaper.questions[i]['score_'+ j];

                         this.questionPaper.questions[i].options[j].content = content;
                         this.questionPaper.questions[i].options[j].score = score;
                       
                    }
                }
            }
        },
        //编辑题目
        editQuestion(index){
            this.formData =JSON.parse(JSON.stringify( this.questionPaper.questions[index]));
             this.$forceUpdate();
        },
        //删除题目
        deleteQuestion(index){
    
            this.questionPaper.questions.splice(index,1);
            let length = this.questionPaper.questions.length;
            //修改题目序号
            for(let i = index; i < length; i++){
                this.questionPaper.questions[i].index = i;
            }
         
            this.$forceUpdate();

        },
        //添加题目
        switchType(type){
            let newForm = {
                index:this.questionPaper.questions.length,
                type:type,
                name:"",
                options:[{},{},{},{}]

            };
            if(type == 0){
                delete newForm.options;
            }
            this.formData =newForm;
            this.$forceUpdate();
        },
        //获取大写字母
        getLetter(index){
            return String.fromCharCode(65 + index);
        },
        //添加选项
        addNewOption(){
            this.formData.options.push({
                content:null,
                score:null
            });
              this.$forceUpdate();
        },
        deleteOption(index){
             this.formData.options.splice(index,1);
               this.$forceUpdate();
        },

        // 题目完成
        submitForm(formName) {
      
            
            if((this.formData.type== 1 || this.formData.type== 2) && this.formData.options.length == 0){
                
                //单选必须有选项
                   this.$modal.msgError("单选或双选题必须要有选项");
                   return 
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //将保存问卷
                    let data = {};
                    Object.assign(data,this.formData);
                    console.log(data)
                    this.questionPaper.questions.splice(data.index,1,data);
                    this.$refs.dataForm.resetFields();
                    this.switchType(this.formData.type);
         
                    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
             this.$forceUpdate();
      
      },

    }
}
</script>

<style  scoped>

/* nav  标题   保存  预览  保存发布等按钮*/
.container{
    position: relative;
    height: 100%;
    background-color: #f2f4f7;

}
.nav{
    width: 100%;
    height: 40px;
    background: #3A4357;
    box-shadow: 0 2px 17px 0 rgba(211, 211, 211, 0.50);
    text-align: center;
    line-height: 40px;
    font-size: 16px;
    color: #A8A8B3;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1000;
}
.nav-btn {
    position: absolute;
    right: 0;
    top: 0;
}

.fr {
    float: right;
}

.nav-btn a {
    float: left;
    width: auto;
    padding: 0 20px;
    color: white;
}
.nav-btn a.completeBtn{
    background-color: #409EFF;
}
.placeholder{
    width: 100%;
    height: 40px;
}
/* 版心 */
.main{
    width: 1200px;
    margin: 0 auto;
}
.mar-top{
    margin-top: 20px;
}
.box{
    padding: 24px 20px 15px 24px;
    background: #fff;
    box-shadow: 0px 2px 10px 0px rgba(237, 238, 240, 0.5);
    border-radius: 8px;
    margin-bottom: 20px;
    position: relative;
    overflow: hidden;
}
/* 主题内容 */
.left{
    width: 280px;

}
.right{
    width: 900px;

}
.editArea{
    display: flex;
    justify-content: space-between;

}
/* new-title */
.new-title>div{
    float: left;
    height: 34px;
    line-height: 34px;
    padding-right: 15px;
}
.new-title>div.label{
        height: 34px;
    line-height: 34px;
    font-size: 12px;
    color: #A8A8B3;
    font-weight: bold;
    padding-right: 15px;
}
/* new-content */
.new-content{
    min-height: 643px;
    position: relative;
}
.btns{
    position: absolute;
    bottom: 15px;
    right: 20px;
  
    display: flex;
    flex-direction: row;
    justify-content: right;
    gap: 10px;
}
.q_number{
    display: inline-block;
    font-weight: bold;
    width: 30px;
}
.q_name{
    color: #A8A8B3;
}
.title_row{
    line-height: 24px;
    font-size: 14px;
}
/* 选项 */
.option{
    display: flex;
    justify-content: start;
    gap: 10px;
}
.option_number{
    text-align: center;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    border: 1px solid #E1EAF4;
    line-height: 30px;
    font-size: 14px;
    color: #646873;
}
.active{
    background-color: #409EFF;
    border: 1px solid #409EFF;
    color: #fff;
}
.option_score{
    width: 65px;
}
.option_text{
    width: 360px;
}
.deleteOption{
    display: none;
}
.option:hover>.deleteOption{
    display: block;
}
/* 题目列表 */
.question:hover>.control{
    display: block;
    font-size: 16px;
}
.control:hover>i{
    color: #409EFF;
    cursor: pointer;
}
.question:hover{
    background-color: #F0F6FF;
}
.question{
    display: flex;
    flex-direction: row;
    justify-content: start;
     position: relative;
    font-size: 12px;
    height: 32px;
    padding: 0px 20px;
    color: #181E33;
    box-sizing: border-box;
}
.question .number{
    width: 16px;
}
.question .control{
    position: absolute;
    right: 20px;
    display: none;

}
.question>div{
    width: 16px;
    line-height: 32px;
    font-weight: bold;
}
.question>div.title{
    width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: left;
}
.left.box{
    padding-left: 0px;
    padding-right: 0px;
}
/* 问卷标题 */
.paper_title{
    display: flex;
    justify-content: start;
    align-items: center;
     padding: 20px;
}
.paper_title>div.label{
    font-weight: bold;
    width: 100px;
}
.paper_title>div.input{
    width: calc(100% - 100px);
}
</style>